/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Communication;

import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import Database.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
 *
 * @author aaron
 */
public class LogReader implements JHaveServerLogGrepperEntryFoundListener, JHaveServerLogGrepperEntryBeganMatchingListener {
    List<JHaveServerLogGrepper> greppers;
    protected String serverId = null;

    public LogReader(String serverId) {
        this.serverId = serverId;
        this.greppers = new ArrayList<JHaveServerLogGrepper>();
        this.addGrepper(new ConnectionJHaveServerLogGrepper());
        this.addGrepper(new VisualizationJHaveServerLogGrepper());
    }

    private void addGrepper(JHaveServerLogGrepper g) {
        g.addEntryBeganMatchingListener(this);
        g.addEntryFoundListener(this);
        this.greppers.add(g);
    }

    private void removeGrepper(JHaveServerLogGrepper g) {
        this.greppers.remove(g);;
    }

    public void inputLine(String lineOfText) {
        //make copy to avoid concurrent blah blah exception
        JHaveServerLogGrepper[] greppersArray = new JHaveServerLogGrepper[0];
        greppersArray = this.greppers.toArray(greppersArray);
        for(JHaveServerLogGrepper grepper : greppersArray) {
            grepper.inputLine(lineOfText);
        }
    }

    static boolean ipAddressExists(String ip) {
        Connection conn = DBConnection.getConn();
        String insertRec = "SELECT IPAddress FROM IPAddress WHERE IPAddress = ?";
        PreparedStatement ps = null;
        boolean exists = false;
        try{
            ps = conn.prepareStatement(insertRec);
            ps.setString(1, ip);
            ResultSet rs = ps.executeQuery();
            rs.last();
            exists = rs.getRow() > 0;
            rs.close();
            ps.close();
        }catch(SQLException e){
            System.out.println("Unable to select IPAddress record");
            return false;
        }
        return exists;
    }

    public void jHaveServerLogEntryFound(JHaveServerLogEntryFoundEvent evt) {
        JHaveServerLogGrepper grepper = (JHaveServerLogGrepper)evt.getSource();
        this.greppers.remove(grepper);
        if(grepper instanceof ConnectionJHaveServerLogGrepper) {
            ConnectionJHaveServerLogGrepper g = (ConnectionJHaveServerLogGrepper)grepper;
            try {
                String date = g.getDateString();
                String connection = g.getConnectionNumber();
                String ip = g.getIPAddress();
                System.out.println(String.format("%s %s C: %s %s", date, serverId, connection, ip));
                DBInsert.insertIntoConnections(connection, date, ip, serverId);
            } catch (ParseException ex) {
                Logger.getLogger(ConsolePipeReader.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JHaveServerLogGrepperMatchNotFinishedException ex) {
                Logger.getLogger(ConsolePipeReader.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else if(grepper instanceof VisualizationJHaveServerLogGrepper) {
            VisualizationJHaveServerLogGrepper g = (VisualizationJHaveServerLogGrepper)grepper;
            try {
                String date = g.getDateString();
                String connection = g.getConnectionNumber();
                String username = g.getUsername() == null ? null : (g.getUsername().equals("no_username") ? null : g.getUsername());
                String vizname = g.getVisualizationName();
                System.out.println(String.format("%s %s V: %s %s %s", date, serverId, connection, username, vizname));
                DBInsert.insertIntoVisualization(connection, serverId, date, username, vizname);
            } catch (ParseException ex) {
                Logger.getLogger(ConsolePipeReader.class.getName()).log(Level.SEVERE, null, ex);
            } catch (JHaveServerLogGrepperMatchNotFinishedException ex) {
                Logger.getLogger(ConsolePipeReader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void jHaveServerLogEntryBeganMatching(JHaveServerLogEntryBeganMatchingEvent evt) {
        JHaveServerLogGrepper grepper = (JHaveServerLogGrepper)evt.getSource();
        if(grepper instanceof ConnectionJHaveServerLogGrepper) {
            this.addGrepper(new ConnectionJHaveServerLogGrepper());
        } else if(grepper instanceof VisualizationJHaveServerLogGrepper) {
            this.addGrepper(new VisualizationJHaveServerLogGrepper());
        }
    }
}
